<!--
 * @Author: whq
 * @Date: 2023-07-24 09:23:29
 * @LastEditTime: 2023-08-23 16:13:49
 * @LastEditors: whq
 * @Description: 
 * @FilePath: \newEraUniform\src\view\HomePage\index.vue
-->
<!--
    * @Author: whq
    * @Date: 2022-12-28 11:28:13
 * @LastEditTime: 2023-08-23 14:49:19
 * @LastEditors: whq
    * @Description: 
 * @FilePath: \newEraUniform\src\view\HomePage\index.vue
   -->
<template>
    <div id="HomePage">     
        <el-dialog v-model="state.dialogTableVisible" :title="state.dialogTitle" destroy-on-close
            :close-on-click-modal="false">
            <el-form label-width="120px" :model="state.targetEditData" :rules="targetEditRules" ref="batchFormRef"
                v-if="state.targetEditData">

                <el-form-item label="批次名称" prop="batchName">
                    <el-input v-model="state.targetEditData.batchName" disabled autocomplete="off" />
                </el-form-item>
                <el-form-item label="所属学年" prop="grade">
                    <el-select v-model="state.targetEditData.grade" :style="{width: '100%'}" placeholder="请选择所属学年" clearable >
                        <el-option v-for="item in schooYearMenu" :key="item" :itemlabel="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所在班级" prop="classes">
                    <el-input v-model="state.targetEditData.classes" placeholder="请输入所在班级几年级几班" required
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="学生姓名" prop="studentName">
                    <el-input v-model="state.targetEditData.studentName" placeholder="请输入学生姓名" required
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="学生联系方式" prop="studentPhone">
                    <el-input v-model.number="state.targetEditData.studentPhone" placeholder="请输入学生联系方式" required
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="老师姓名" prop="teacherName">
                    <el-input v-model="state.targetEditData.teacherName" placeholder="请输入老师姓名" required
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="老师联系方式" prop="teacherPhone">
                    <el-input v-model.number="state.targetEditData.teacherPhone" placeholder="请输入老师联系方式" required
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch v-model="state.targetEditData.status" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
            <el-form label-width="120px" :model="state.batchFormInline" :rules="batchRules" ref="batchFormRef" v-else>
                <el-form-item label="数量" required prop="num">
                    <el-input type="number" v-model.number="state.batchFormInline.num" step="1" min="0" max="5000"
                        autocomplete="off" @change="(e: any) => handleClick('DialogTableVisibleNum', e)" />
                </el-form-item>
                <el-form-item label="批次名称" required prop="batchName">
                    <el-input v-model="state.batchFormInline.batchName" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="state.dialogTableVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleClick('DialogTableVisibleSubmit')">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <div class="tabs-query">
            <el-form :inline="true" :model="state.formInline" class="demo-form-inline">
                <el-form-item label="批次名称">
                    <el-select v-model="state.formInline.batchName" placeholder="批次名称" @change="handleClick('Submit')"
                        clearable>
                        <el-option v-for="item in state.batchNameList" :key="item" :itemlabel="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属学年">
                    <el-select v-model="state.formInline.grade" placeholder="所属学年" clearable>
                        <el-option v-for="item in schooYearMenu" :key="item" :itemlabel="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所在班级">
                    <el-input v-model="state.formInline.classes" placeholder="请输入所在班级" clearable />
                </el-form-item>
                <el-form-item label="学生姓名">
                    <el-input v-model="state.formInline.studentName" placeholder="请输入学生姓名" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleClick('Submit')">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleClick('ALLQRcode')">下载批次二维码</el-button>
                </el-form-item>
                <!-- <el-form-item>
                    <el-button type="primary" @click="handleClick('QRcode')">下载选中二维码</el-button>
                </el-form-item> -->
                <el-form-item>
                    <el-button type="primary" @click="handleClick('ADDBatchName')">新增批次校服</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="tabs-box">
            <el-table ref="multipleTableRef" :data="state.dataList" style="width: 100%"
                @selection-change="(e: any) => handleClick('SelectionChange', e)">
                <!-- <el-table-column type="selection" width="55" /> -->
                <el-table-column label="批次名称">
                    <template #default="scope">{{ scope.row.batchName }}</template>
                </el-table-column>
                <el-table-column label="所在班级">
                    <template #default="scope">{{ scope.row.classes }}</template>
                </el-table-column>
                <el-table-column label="所属学年">
                    <template #default="scope">{{ scope.row.grade }}</template>
                </el-table-column>
                <el-table-column label="学生姓名">
                    <template #default="scope">{{ scope.row.studentName }}</template>
                </el-table-column>
                <el-table-column label="学生联系方式">
                    <template #default="scope">{{ scope.row.studentPhone }}</template>
                </el-table-column>
                <el-table-column label="老师姓名">
                    <template #default="scope">{{ scope.row.teacherName }}</template>
                </el-table-column>
                <el-table-column label="老师联系方式">
                    <template #default="scope">{{ scope.row.teacherPhone }}</template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag disable-transitions :type="scope.row.status == 1 ? 'success' : 'warning'">
                            {{ scope.row.status == 1 ? '已绑定' : '未绑定' }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column fixed="right" label="操作">
                    <template #default="scope">
                        <el-button type="primary" @click="handleClick('Edit', scope.row)">编辑</el-button>
                        <el-button type="danger" @click="handleClick('Del', scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-pagination v-model:currentPage="state.pages.currentPage" :page-sizes="[20, 30, 50, 100]"
            :page-size="state.pages.pageSize" layout=" prev, pager, next, jumper,total, sizes," :background="true"
            :total="state.pages.total" @size-change="(e: any) => handleClick('SizeChange', e)"
            @current-change="(e: any) => handleClick('CurrentChange', e)" />
        <div class="qrcode-pic">
            <div v-for="(v, i) in state.multipleSelection" :key="i">
                <div ref="codeItem"></div>
            </div>
        </div>
        <!-- <div v-for="(v, i) in state.QRcodeArr" :key="i">
            <el-image style="width: 100px; height: 100px" :src="v.imgurl" fit="fill" />
        </div> -->
        <!-- 必须存在的dom 生成的二维码通过这种方式隐藏 -->
        <div id="qrid" :style="{ 'margin-top': '-99999999999999999px', position: 'fixed' }"></div>
        <!-- 对话框 -->

    </div>
</template>
<script setup lang="ts">
import globals from '@/store/globals'
import { ref, onMounted, reactive, watch } from 'vue'
import QRcode from "qrcodejs2-fix";
import html2canvas from 'html2canvas'
import JSZip from "jszip"
import FileSaver from 'file-saver';
import { ElLoading, ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { schooYearMenu } from './json';
import { getBatchNameListApi, getClothingEditApi, getClothingListApi, getClothingRemoveApi, geTinitClothingInfoApi } from './services';
const codeItem = ref<any>(null)

const state = reactive<any>({
    QRcodeArr: [],
    dataList: [],
    multipleSelection: [],
    formInline: {},
    batchNameList: [],
    dialogTableVisible: false,
    batchFormInline: {
        num: '',
        batchName: '',
    },
    handleClickType: '',
    dialogTitle: '',
    targetEditData: null,
    pages: {
        total: 500,//总数据
        currentPage: 1,// 当前页数
        pageSize: 20,// 一页显示多少条
    }
})

const batchFormRef = ref<any>()
const batchRules = reactive<any>({
    'num': [
        { required: true, message: '请填写数量', trigger: 'blur' },
    ],
    batchName: [
        { required: true, message: '请填写批次名称', trigger: 'blur' },
    ],
})
const targetEditRules = reactive<any>({
    grade: [
        { required: true, message: '请填写所属学年', trigger: 'blur' },
    ],
    classes: [
        { required: true, message: '请填写班级姓名', trigger: 'blur' },
    ],
    studentName: [
        { required: true, message: '请填写学生姓名', trigger: 'blur' },
    ],
    studentPhone: [
        {
            min: 11,
            max: 11,
            message: '手机号长度在 11 个数字',
            trigger: 'blur'
        },
        {
            validator: (rule: any, value: any, callback: any) => {
                if (value) {
                    var reg = /^[1][3,4,5,7,8][0-9]{9}$/;
                    if (!reg.test(value)) {
                        callback(new Error('请请正确输入学生联系方式'))
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }

            },
            trigger: 'blur'
        }
    ],
    teacherName: [
        { required: true, message: '请填写老师姓名', trigger: 'blur' },
    ],
    teacherPhone: [
        {
            min: 11,
            max: 11,
            message: '手机号长度在 11 个数字',
            trigger: 'blur'
        },
        {
            validator: (rule: any, value: any, callback: any) => {
                if (value) {
                    var reg = /^[1][3,4,5,7,8][0-9]{9}$/;
                    if (!reg.test(value)) {
                        callback(new Error('请请正确输入老师联系方式'))
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }

            },
            trigger: 'blur'
        }
    ],
})







// 所有事件触发处理
const handleClick = async (type: any, data?: any) => {
    state.handleClickType = type
    switch (type) {
        // 下载选中的数据的二维码
        case 'QRcode':

            if (!state.multipleSelection.length) {
                return ElMessage({
                    message: '请选择要下载的信息',
                    type: 'warning',
                })
            }
            await setQRcodeArr()
            break;
        // 下载符合条件数据的二维码
        case 'ALLQRcode':

            if (!state.formInline.batchName) {
                return ElMessage({
                    message: '请选择批次',
                    type: 'warning',
                })
            }
            window.open(import.meta.env.VITE_APP_AXIOS_API + '/v1/clothing/clothingExportExcel?batchName=' + state.formInline.batchName)
            break;
        // 当前选中页码
        case 'CurrentChange':
            state.pages.currentPage = data
            getClothingList(state.formInline)
            break;
        // 页码选择
        case 'SizeChange':
            state.pages.pageSize = data
            getClothingList(state.formInline)
        // 列表多选选中
        case 'SelectionChange':
            state.multipleSelection = data
            break;
        // 新增批次
        case 'ADDBatchName':
            state.dialogTitle = '添加批次校服'
            state.targetEditData = null
            state.dialogTableVisible = true
            state.batchFormInline = {
                num: '',
                batchName: '',
            }
            break;
        // 弹框确认
        case 'DialogTableVisibleSubmit':

            batchFormRef.value.validate(async (valid: any) => {
                if (valid) {

                    if (state.targetEditData) {
                        // 弹框编辑
                        await getClothingEditApi(state.targetEditData)
                    } else {
                        await geTinitClothingInfoApi(state.batchFormInline)
                        getBatchNameList()
                    }
                    getClothingList(state.formInline)
                    state.dialogTableVisible = false
                } else {
                    console.log('错误!')
                }
            })

            // state.dialogTableVisible = false
            break;
        // 弹框 数量验证
        case 'DialogTableVisibleNum':

            if (data > 5000) {
                state.batchFormInline.num = 5000
            }
            break;
        // 服装编辑
        case 'Edit':
            console.log(data, "===当前编辑的数据==");

            state.dialogTitle = '编辑'
            state.targetEditData = data
            state.dialogTableVisible = true
            break;
        // 服装编辑
        case 'Del':
            ElMessageBox.confirm(
                '确定要删除该条校服数据吗?',
                'Warning',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(async () => {
                    await getClothingRemoveApi({ clothingId: data.clothingId })
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    await getClothingList(state.formInline)
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
            break;
        // 表单查询提交
        case 'Submit':

            getClothingList(state.formInline)
            break;

        default:
            break;
    }

}
//  生成二维码图片
const setQRcodeArr = async () => {
    let loadingInstance = ElLoading.service({ fullscreen: true })
    let qridElement: any = document.querySelector('#qrid')
    qridElement.innerHTML = ''
    for (const itemIterator of state.multipleSelection) {
        let newDivElement: any = document.createElement("div")
        newDivElement.innerHTML = "";

        var qrcode = new QRcode(newDivElement, {
            text: 'https://www.baidu.com/', //二维码内容
            width: 120,
            height: 120,
            render: 'table',
            colorDark: "#333333", //二维码颜色
            colorLight: "#ffffff", //二维码背景色
            correctLevel: QRcode.CorrectLevel.H
        })
        qridElement.appendChild(newDivElement)

        // 创建画布放二维码，方便下载
        let canvas: any = document.createElement("canvas"),
            scale = 1;
        canvas.width = 120;
        canvas.height = 120;
        canvas.getContext("2d").scale(scale, scale);
        let opts = {
            canvas: canvas,
            logging: false,
            width: 120,
            height: 120,
            useCORS: true,
            allowTaint: true,//允许跨域图片
            scale: 1, // 处理模糊问题
            dpi: 300, // 处理模糊问题
            background: "#ffffff",
        }
        // 生成二维码图片
        await html2canvas(newDivElement, opts).then((canvas) => {
            const qrContentImage = canvas.toDataURL('image/png', 1.0);// 生成的图片
            state.QRcodeArr.push({
                ...itemIterator,
                imgurl: qrContentImage
            })

        }).catch(function (reason) {
            console.log(reason);
        });
        //下载文件

    }
    qridElement.innerHTML = ''
    //创建压缩对象
    var zip = new JSZip();

    for (const QRcodeIterator of state.QRcodeArr) {
        zip.file(`${QRcodeIterator.id}.png`, QRcodeIterator.imgurl.replace(/^data:image\/(png|jpg);base64,/, ""), { base64: true }); //第一个参数是图片名字和后缀
    }

    //下载压缩包
    zip.generateAsync({ type: "blob" }).then(function (content: any) {
        FileSaver(content, "二维码.zip");
    });
    loadingInstance.close()
}
// 获取校服数据列表
const getClothingList = async (data: any = {}) => {
    let loadingInstance = ElLoading.service({ fullscreen: true })

    let newData = {
        currentPage: state.pages.currentPage,
        pageSize: state.pages.pageSize,
        ...data
    }
    try {
        let resData: any = await getClothingListApi(newData)

        state.pages.pageSize = resData.pageSize
        state.pages.currentPage = resData.currentPage
        state.pages.total = resData.total
        state.dataList = resData.data
    } catch (error) {

    }
    loadingInstance.close()
}
// 获取批次列表
const getBatchNameList = async (data: any = {}) => {
    try {
        let resData: any = await getBatchNameListApi()
        state.batchNameList = resData
    } catch (error) {

    }
}

onMounted(() => {
    getClothingList()
    getBatchNameList()

})

</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>